package com.ts.dto;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.log.Log;

/**
 *
 * @author karthikeyanc
 */
public class FileWrapper implements Serializable {

    @Logger
    Log log;
    private InputStream uploadedFile;
    private String fileName;

    /**
     * @return the uploadedFile
     */
    public InputStream getUploadedFile() {
        return uploadedFile;
    }

    public boolean isEmpty() {
        int avai = 0;
        boolean isEmpty = false;
        try {
            avai = uploadedFile.available();
            if (avai == 0) {
                isEmpty = true;
            }
        } catch (Exception e) {
            isEmpty = true;
        }

        return isEmpty;
    }

    /**
     * @param uploadedFile the uploadedFile to set
     */
    public void setUploadedFile(InputStream uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public void saveToDisk(String location) {

        System.out.println("Uploaded file name is :" + fileName);

        FileOutputStream fos = null;

        try {
            File parentDir = new File(location);
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }

            File file = new File(location + fileName);



            fos = new FileOutputStream(file);
            byte[] b = new byte[102400];
            int readCnt = 0;
            while ((readCnt = uploadedFile.read(b)) != -1) {
                fos.write(b, 0, readCnt);
                fos.flush();
            }

        } catch (Exception ex) {
            log.error("exception in storing file", ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                log.error("exception in closing file", ex);
            }
        }
    }

    public long getFileSize(String location) {
        File file = new File(location + fileName);
        if (file == null) {
            log.debug("Uploaded file is null and hence returning size zero");
            return 0;
        }
        return file.length();

    }

  

    /**
     * @return the fileName
     */
    public String getFileName() {

        return fileName;
    }

    /**
     * @param fileName the fileName to set
     */
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
